import { defineStore } from 'pinia'
import { login, register, getUserInfo, updateUserInfo, changePassword } from '@/api/user.js'

export const useUserStore = defineStore('user', {
  state: () => ({
    // 用户信息
    userInfo: null,
    // 登录状态
    isLoggedIn: false,
    // token
    token: uni.getStorageSync('token') || null
  }),

  getters: {
    // 获取用户信息
    getUserInfo: (state) => state.userInfo,
    // 获取登录状态
    getLoginStatus: (state) => state.isLoggedIn,
    // 获取token
    getToken: (state) => state.token
  },

  actions: {
    // 用户登录
    async login(loginData) {
      try {
        const response = await login(loginData)
        if (response.code === 200) {
          // 登录成功，获取用户信息
          const userResponse = await getUserInfo(loginData.username)
          if (userResponse.code === 200) {
            this.userInfo = userResponse.obj
            this.isLoggedIn = true
            this.token = 'mock_token_' + Date.now() // 模拟token，实际应该从后端获取
            
            // 保存到本地存储
            uni.setStorageSync('token', this.token)
            uni.setStorageSync('userInfo', this.userInfo)
            
            console.log('登录成功，用户信息:', this.userInfo)
            return { success: true, message: '登录成功' }
          } else {
            return { success: false, message: userResponse.msg || '获取用户信息失败' }
          }
        }
        return { success: false, message: response.msg || '登录失败' }
      } catch (error) {
        console.error('登录错误:', error)
        return { success: false, message: '网络错误，请稍后重试' }
      }
    },

    // 用户注册
    async register(registerData) {
      try {
        console.log('开始注册请求:', registerData)
        const response = await register(registerData)
        console.log('注册响应:', response)
        
        if (response.code === 200) {
          return { success: true, message: '注册成功' }
        }
        return { success: false, message: response.msg || '注册失败' }
      } catch (error) {
        console.error('注册错误:', error)
        return { success: false, message: '网络错误，请稍后重试' }
      }
    },

    // 获取用户信息
    async fetchUserInfo(username) {
      try {
        const response = await getUserInfo(username)
        if (response.code === 200) {
          this.userInfo = response.obj
          return { success: true, data: response.obj }
        }
        return { success: false, message: response.msg || '获取用户信息失败' }
      } catch (error) {
        console.error('获取用户信息错误:', error)
        return { success: false, message: '网络错误，请稍后重试' }
      }
    },

    // 用户登出
    logout() {
      this.userInfo = null
      this.isLoggedIn = false
      this.token = null
      
      // 清除本地存储
      uni.removeStorageSync('token')
      uni.removeStorageSync('userInfo')
      
      // 跳转到登录页
      uni.reLaunch({
        url: '/pages/login/login'
      })
    },

    // 检查登录状态
    checkLoginStatus() {
      const token = uni.getStorageSync('token')
      const userInfo = uni.getStorageSync('userInfo')
      
      if (token && userInfo) {
        this.token = token
        this.userInfo = userInfo
        this.isLoggedIn = true
        return true
      }
      return false
    },

    // 更新用户信息
    updateUserInfo(userInfo) {
      this.userInfo = userInfo
      uni.setStorageSync('userInfo', userInfo)
    },

    // 更新用户资料
    async updateProfile(profileData) {
      try {
        const response = await updateUserInfo(profileData)
        if (response.code === 200) {
          // 更新本地用户信息
          this.userInfo = { ...this.userInfo, ...profileData }
          uni.setStorageSync('userInfo', this.userInfo)
          return { success: true, message: '更新成功' }
        }
        return { success: false, message: response.msg || '更新失败' }
      } catch (error) {
        console.error('更新用户资料错误:', error)
        return { success: false, message: '网络错误，请稍后重试' }
      }
    },

    // 修改密码
    async changeUserPassword(passwordData) {
      try {
        const response = await changePassword(passwordData)
        if (response.code === 200) {
          return { success: true, message: '密码修改成功' }
        }
        return { success: false, message: response.msg || '密码修改失败' }
      } catch (error) {
        console.error('修改密码错误:', error)
        return { success: false, message: '网络错误，请稍后重试' }
      }
    }
  }
})
